import { useState, useEffect, useRef } from 'react'
import { useHistory } from 'react-router-dom'
import dayjs from 'dayjs'
import { List, DatePicker, Drawer, Modal } from 'antd-mobile'
import classnames from 'classnames'
import EditList from './components/EditList'
import NavBar from '../../../components/NavBar'
import styles from './index.module.scss'
import { http, removeToken } from '@/utils'

import EditInput from './components/EditInput'

// antd组件
const Item = List.Item
const {alert} = Modal
// 抽屉弹框数据
const genderItems = [
  { text: '男', value: '0' },
  { text: '女', value: '1' },
]
const hedpicItems = [
  { text: '拍照', value: 'picture' },
  { text: '本地相册', value: 'local' },
]
// 个人信息页面
const ProfileEdit = () => {
  const history=useHistory()
  // 创建在组件中操控DOM元素的方法。还有一个用法，维持定时器的数值
  const fileRef = useRef()
  // 用户信息状态
  const [userInfo, setUserInfo] = useState({})
  // 性别+头像抽屉状态
  const [listDrawer, setListDrawer] = useState({
    open: false,
    type: 'photo',
  })
  // 昵称+简介抽屉状态
  const [nameDrawer, setNameDrawer] = useState({
    open: false,
    type: 'name',
  })
  // 显示获取用户信息
  useEffect(() => {
    const getUserInfo = async () => {
      try {
        const res = await http.get('/user/profile')
        setUserInfo(res.data.data)
      } catch (e) {}
    }
    getUserInfo()
  }, [])
  // 打开昵称抽屉
  const openName = () => {
    setNameDrawer({
      open: true,
      type: 'name',
    })
  }
  // 打开简介抽屉
  const openIntro=()=>{
    setNameDrawer({
      open: true,
      type: 'intro',
    })
  }
  //打开头像抽屉
  const onPhotoOpen = () => {
    setListDrawer({
      open: true,
      type: 'photo',
    })
  }
  //打开性别抽屉
  const onGenderOpen = () => {
    setListDrawer({
      open: true,
      type: 'gender',
    })
  }
  //关闭性别抽屉
  const onGenderClose = () => {
    setListDrawer({
      ...listDrawer,
      open: false,
    })
  }
  // 更换头像 发送请求
  const onChangePhoto = async e => {
    try {
      // console.log(e);
      const file = e.target.files[0]
      // console.log(file);
      if (!file) {
        return
      }
      // 创建一个空对象上传数据，FormData接口提供了一种表示表单数据的键值对 key/value 的构造方式，将新增数据发送出去，如果送出时的编码类型被设为 "multipart/form-data"，它会使用和表单一样的格式。
      const formData = new FormData()
      console.log(formData)
      // formData的file里追加一个photo属性,并把上传图片的地址一起追加进去
      // 没有这一步图片无法上传
      formData.append('photo', file)
      // console.log(file);

      const res = await http.patch('/user/photo', formData)
      // console.log(res);
      setUserInfo({
        ...userInfo,
        photo: res.data.data.photo,
      })
    } finally {
      onGenderClose()
    }
  }
  //点击更换头像
  const changePhoto = () => {
    fileRef.current.click()
  }
  // 更改性别 发送请求
  const changeGander = async gender => {
    try {
      await http.patch('/user/profile', { gender })
      setUserInfo({
        ...userInfo,
        gender: +gender,
      })
      onGenderClose()
    } catch {}
  }
  const { birthday, gender, intro='', name, photo } = userInfo
  // 关闭昵称+简介抽屉
  const closeName = () => {
    setNameDrawer({
      ...nameDrawer,
      open: false,
    })
  }
  // 更新昵称
  const onUpdateName = async name => {
    try {
      await http.patch('/user/profile', { name })
      setUserInfo({ ...userInfo, name })
      closeName()
    } catch {}
  }
  // 更新简介
  const onUpdateIntro = async intro => {
    try {
      await http.patch('/user/profile', { intro })
      setUserInfo({ ...userInfo, intro })
      closeName()
    } catch {}
  }

  // 修改生日
  const onBirthdayChange = async date => {
    const birthday = dayjs(date).format('YYYY-MM-DD')

    try {
      await http.patch('/user/profile', {
        birthday
      })

      setUserInfo({
        ...userInfo,
        birthday
      })
    } catch {}
  }
  // 昵称数据
  const nameConfig = {
    text: '昵称',
    value: name,
  }
  // 简介数据
  const introConfig = {
    text: '简介',
    value: intro,
  }
  return (
    <div className={styles.root}>
      <div className="content">
        <NavBar onClick={() => history.go(-1)}>个人信息</NavBar>
        <div className="wrapper">
          <List className="profile-list">
            <Item
              arrow="horizontal"
              extra={
                <span className="avatar-wrapper">
                  <img src={photo || 'http://toutiao.itheima.net/images/user_head.jpg'} alt="" />
                </span>
              }
              onClick={onPhotoOpen}
            >
              头像
            </Item>
            <Item arrow="horizontal" onClick={openName} extra={name || '黑马先锋'}>
              昵称
            </Item>
            <Item
              arrow="horizontal"
              onClick={openIntro}
              extra={<span className={classnames('intro',intro&& 'normal')}>{intro || '未填写'}</span>}
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item arrow="horizontal" extra={gender === 0 ? '男' : '女'} onClick={onGenderOpen}>
              性别
            </Item>
            <DatePicker
              mode="date"
              value={new Date(birthday)}
              onChange={onBirthdayChange}
              title="选择年月日"
              minDate={new Date(1900, 1, 1, 0, 0, 0)}
              maxDate={new Date()}
            >
              <Item arrow="horizontal">生日</Item>
            </DatePicker>
          </List>
          {/* 点击本地选择打开图片选择的窗口 */}
          <input type="file" hidden ref={fileRef} onChange={onChangePhoto} />
        </div>

        <div className="logout">
          <button
            className="btn"
            onClick={() =>
              alert('退出登录', '确定退出？', [
                { text: '取消' },
                { text: '确定', onPress: () => {
                  removeToken()
                  history.push('/login') }},
              ])
            }
          >
            退出登录
          </button>
        </div>
      </div>

      {/* 头像、性别 */}
      <Drawer
        open={listDrawer.open}
        onOpenChange={onGenderClose}
        sidebar={
          <EditList
            items={listDrawer.type === 'photo' ? hedpicItems : genderItems}
            onClose={onGenderClose}
            changeGander={listDrawer.type === 'photo' ? changePhoto : changeGander}
          />
        }
        className="drawer-list"
        position="bottom"
      >
        {''}
      </Drawer>
      {/* 昵称、简介 */}
      <Drawer
        open={nameDrawer.open}
        className="drawer"
        position="right"
        sidebar={
          <EditInput
            config={nameDrawer.type === 'name' ? nameConfig : introConfig}
            onUpdate={nameDrawer.type === 'name' ? onUpdateName : onUpdateIntro}
            onClose={closeName}
          />
        }
      >
        {''}
      </Drawer>
    </div>
  )
}

export default ProfileEdit
